import 'dart:async';
import 'dart:convert';
import 'dart:developer' as developer;
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import '../../../core/controllers/ring_controller.dart';
import '../../../services/ring_service.dart';
import '../../../services/device_sn_manager.dart';
import '../../../core/repository/default_api.dart';

/// 时间范围
enum BloodOxygenTimeRange { day, week, month }

/// 血氧数据模型（用于页面展示）
class BloodOxygenViewData {
  final DateTime date;
  final int average;
  final List<int> hourly;
  const BloodOxygenViewData({
    required this.date,
    required this.average,
    required this.hourly,
  });
}

/// 血氧监测数据点
class BloodOxygenDataPoint {
  final String code; // 时间 "HH:mm" 或日期 "10/26"
  final int? value; // 血氧值（日视图使用）
  final int maxValue; // 最高值（周/月视图使用）
  final int minValue; // 最低值（周/月视图使用）
  final int number; // 数据点数量

  BloodOxygenDataPoint({
    required this.code,
    this.value,
    required this.maxValue,
    required this.minValue,
    required this.number,
  });

  factory BloodOxygenDataPoint.fromJson(Map<String, dynamic> json) {
    int parseValue(dynamic value) {
      if (value == null) return 0;
      if (value is int) return value;
      if (value is double) return value.toInt();
      if (value is String) return int.tryParse(value) ?? 0;
      return 0;
    }

    return BloodOxygenDataPoint(
      code: json['code']?.toString() ?? '',
      value: json['value'] != null ? parseValue(json['value']) : null,
      maxValue: parseValue(json['maxValue']),
      minValue: parseValue(json['minValue']),
      number: parseValue(json['number']),
    );
  }
}

/// 血氧趋势图数据模型（queryBloodOxygenMonitor接口）
class BloodOxygenMonitorData {
  final int average; // 平均血氧
  final String? dateStart;
  final String? dateEnd;
  final String recordDate; // 记录日期
  final String weekName; // 星期
  final String endTime;
  final int maxValue; // 最高值
  final int minValue; // 最低值
  final List<BloodOxygenDataPoint> manualInfoVOS;
  final List<BloodOxygenDataPoint> automaticInfoVOS; // 自动监测数据点

  BloodOxygenMonitorData({
    required this.average,
    this.dateStart,
    this.dateEnd,
    required this.recordDate,
    required this.weekName,
    required this.endTime,
    required this.maxValue,
    required this.minValue,
    required this.manualInfoVOS,
    required this.automaticInfoVOS,
  });

  factory BloodOxygenMonitorData.fromJson(Map<String, dynamic> json) {
    int parseInt(dynamic value) {
      if (value == null) return 0;
      if (value is int) return value;
      if (value is double) return value.toInt();
      if (value is String) return int.tryParse(value) ?? 0;
      return 0;
    }

    final result = BloodOxygenMonitorData(
      average: parseInt(json['average']),
      dateStart: json['dateStart']?.toString(),
      dateEnd: json['dateEnd']?.toString(),
      recordDate: json['recordDate']?.toString() ?? '',
      weekName: json['weekName']?.toString() ?? '',
      endTime: json['endTime']?.toString() ?? '',
      maxValue: parseInt(json['maxValue']),
      minValue: parseInt(json['minValue']),
      manualInfoVOS: (json['manualInfoVOS'] as List<dynamic>?)
              ?.map((e) =>
                  BloodOxygenDataPoint.fromJson(e as Map<String, dynamic>))
              .toList() ??
          [],
      automaticInfoVOS: (json['automaticInfoVOS'] as List<dynamic>?)
              ?.map((e) =>
                  BloodOxygenDataPoint.fromJson(e as Map<String, dynamic>))
              .toList() ??
          [],
    );

    developer.log(
        '✅ 趋势图数据: 平均=${result.average}%, 最高=${result.maxValue}%, 最低=${result.minValue}%, 数据点=${result.automaticInfoVOS.length}个',
        name: 'BloodOxygen');
    return result;
  }
}

/// 本月夜间血氧监测数据模型（queryBloodOxygenAverage接口）
class BloodOxygenAverageData {
  final int bloodOxygenAverage; // 睡眠时平均血氧饱和度
  final int minBloodOxygen; // 睡眠时最低血氧饱和度
  final int bloodOxygenRate; // 睡眠时血氧的低血氧占比（TST90）
  final int effectiveMeasurement; // 有效测量次数
  final int exceptionCount; // 异常次数

  BloodOxygenAverageData({
    required this.bloodOxygenAverage,
    required this.minBloodOxygen,
    required this.bloodOxygenRate,
    required this.effectiveMeasurement,
    required this.exceptionCount,
  });

  factory BloodOxygenAverageData.fromJson(Map<String, dynamic> json) {
    int parseInt(dynamic value) {
      if (value == null) return 0;
      if (value is int) return value;
      if (value is double) return value.toInt();
      if (value is String) return int.tryParse(value) ?? 0;
      return 0;
    }

    final result = BloodOxygenAverageData(
      bloodOxygenAverage: parseInt(json['bloodOxygenAverage']),
      minBloodOxygen: parseInt(json['minBloodOxygen']),
      bloodOxygenRate: parseInt(json['bloodOxygenRate']),
      effectiveMeasurement: parseInt(json['effectiveMeasurement']),
      exceptionCount: parseInt(json['exceptionCount']),
    );

    developer.log(
        '✅ 月度监测数据: 平均=${result.bloodOxygenAverage}%, 最低=${result.minBloodOxygen}%, 占比=${result.bloodOxygenRate}%',
        name: 'BloodOxygen');
    return result;
  }
}

/// 血氧饱和度控制器
class BloodOxygenLogic extends GetxController {
  late RingController _ringController;
  late RingService _ringService;
  RingController get ringController => _ringController;

  final Rx<BloodOxygenTimeRange> currentRange = BloodOxygenTimeRange.day.obs;
  final RxInt selectedIndex = (-1).obs;
  final RxDouble dragLineX = 0.0.obs;
  final Rx<BloodOxygenViewData?> data = Rx<BloodOxygenViewData?>(null);
  final RxBool isLoading = false.obs;

  // 接口数据 - 趋势图数据（queryBloodOxygenMonitor）
  final Rx<BloodOxygenMonitorData?> monitorData =
      Rx<BloodOxygenMonitorData?>(null);
  // 接口数据 - 月度监测数据（queryBloodOxygenAverage）
  final Rx<BloodOxygenAverageData?> averageData =
      Rx<BloodOxygenAverageData?>(null);

  @override
  void onInit() {
    super.onInit();
    _ringController = Get.find<RingController>();
    _ringService = Get.find<RingService>();
    // 延迟调用二级页接口
    Future.delayed(const Duration(milliseconds: 100), () {
      _fetchBloodOxygenSecondaryData();
    });
  }

  void setTimeRange(BloodOxygenTimeRange range) {
    currentRange.value = range;
    selectedIndex.value = -1;
    // 切换时间范围时重新获取数据
    _fetchBloodOxygenSecondaryData();
  }






  /// 获取日期标题（根据时间范围使用不同字段）
  String getDateTitle() {
    final monitor = monitorData.value;
    
    if (monitor != null) {
      // 周和月视图使用 dateStart 和 dateEnd
      if (currentRange.value == BloodOxygenTimeRange.week ||
          currentRange.value == BloodOxygenTimeRange.month) {
        if (monitor.dateStart != null && monitor.dateEnd != null) {
          return '${monitor.dateStart} - ${monitor.dateEnd}';
        }
      }
      
      // 日视图使用 recordDate 和 weekName
      if (currentRange.value == BloodOxygenTimeRange.day &&
          monitor.recordDate.isNotEmpty) {
        return '${monitor.recordDate}，${monitor.weekName}';
      }
    }

    // 降级方案：使用当前日期
    final d = DateTime.now();
    const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    final weekday = weekdays[(d.weekday - 1).clamp(0, 6)];
    return '${d.year}年${d.month.toString().padLeft(2, '0')}月${d.day.toString().padLeft(2, '0')}日，$weekday';
  }

  void handlePanUpdate(double dx, double width, int len) {
    final index = (dx / (width / len)).floor();
    if (index >= 0 && index < len) {
      selectedIndex.value = index;
      dragLineX.value = dx;
    }
  }

  void handlePanEnd() {
    dragLineX.value = 0;
  }

  /// 获取血氧二级页数据
  Future<void> _fetchBloodOxygenSecondaryData() async {
    try {
      // 获取设备序列号
      final deviceSnManager = Get.find<DeviceSnManager>();
      final deviceSn = deviceSnManager.getDeviceSn();
      if (deviceSn.isEmpty) {
        developer.log('❌ 设备SN为空，无法获取血氧数据', name: 'BloodOxygen');
        return;
      }

      // 获取当前日期
      final now = DateTime.now();
      final recordDate =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      // 并行调用两个血氧相关接口
      await Future.wait([
        _fetchBloodOxygenAverage(deviceSn, recordDate),
        _fetchBloodOxygenMonitor(deviceSn, recordDate),
      ]);
    } catch (e) {
      developer.log('❌ 获取血氧数据异常: $e', name: 'BloodOxygen');
    }
  }

  /// 获取当前时间范围对应的type值
  String _getTypeFromTimeRange() {
    switch (currentRange.value) {
      case BloodOxygenTimeRange.day:
        return '1';
      case BloodOxygenTimeRange.week:
        return '2';
      case BloodOxygenTimeRange.month:
        return '3';
    }
  }

  /// 获取血氧平均值
  Future<void> _fetchBloodOxygenAverage(
      String deviceSn, String recordDate) async {
    try {
      final response =
          await DefaultApi().queryBloodOxygenAverageGet<Map<String, dynamic>>(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: false,
        isShowLoading: false,
      );

      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null && data is Map<String, dynamic>) {
          final parsedData = BloodOxygenMonitorData.fromJson(data);
          monitorData.value = parsedData;
        }
      }
    } catch (e) {
      developer.log('❌ 获取血氧平均值失败: $e', name: 'BloodOxygen');
    }
  }

  /// 获取夜间血氧监测
  Future<void> _fetchBloodOxygenMonitor(
      String deviceSn, String recordDate) async {
    try {
      final response =
          await DefaultApi().queryBloodOxygenMonitorGet<Map<String, dynamic>>(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: _getTypeFromTimeRange(),
        isShowErrMsg: false,
        isShowLoading: false,
      );
      if (response != null && response['code'] == 200) {
        final data = response['data'];
        if (data != null && data is Map<String, dynamic>) {
          final parsedData = BloodOxygenAverageData.fromJson(data);
          averageData.value = parsedData;
        }
      }
      
    } catch (e) {
      developer.log('❌ 获取夜间血氧监测失败: $e', name: 'BloodOxygen');
    }
  }

  /// 根据指定日期加载数据
  void loadDataByDate(String recordDate) {
    developer.log('📅 根据日期加载血氧数据: $recordDate', name: 'BloodOxygen');
    
    // 获取设备SN
    final deviceSnManager = Get.find<DeviceSnManager>();
    final deviceSn = deviceSnManager.getDeviceSn();

    if (deviceSn.isEmpty) {
      developer.log('⚠️ 设备SN为空，无法获取血氧数据', name: 'BloodOxygen');
      return;
    }

    // 并行调用两个血氧相关接口
    Future.wait([
      _fetchBloodOxygenAverage(deviceSn, recordDate),
      _fetchBloodOxygenMonitor(deviceSn, recordDate),
    ]);
  }
}
